package com.nulldev.util.networking.async2.tcp.listeners;

import com.nulldev.util.networking.async2.ByteArrayBuilder;
import com.nulldev.util.networking.async2.DataFrame;

public class TCPClientConnectionMessageCollector {

	private TCPClientConnection fMyClient;
	private final byte[] fETXStr;
	private final ByteArrayBuilder fIncomingDataBuffer;
	private int fIndexOfETX;
	private final int fETXLength;

	public TCPClientConnectionMessageCollector(TCPClientConnection myClient, char splitter) {
		fMyClient = myClient;
		fETXStr = String.valueOf(splitter).getBytes();
		fETXLength = fETXStr.length;
		fIncomingDataBuffer = new ByteArrayBuilder();
	}

	public TCPClientConnectionMessageCollector(TCPClientConnection myClient, String splitter) {
		fMyClient = myClient;
		fETXStr = splitter.getBytes();
		fETXLength = fETXStr.length;
		fIncomingDataBuffer = new ByteArrayBuilder();
	}

	public void appendData(byte[] bytes) {
		try {
			fIncomingDataBuffer.append(bytes);
			fIndexOfETX = fIncomingDataBuffer.indexOf(fETXStr);
			while (fIndexOfETX > -1) {
				fMyClient.getTCPListener().getTCPServer().onDataReceive(fMyClient, new DataFrame(fIncomingDataBuffer.subList(0, fIndexOfETX)));
				fIncomingDataBuffer.delete(0, fIndexOfETX + fETXLength);
				fIndexOfETX = fIncomingDataBuffer.indexOf(fETXStr);
			}
		} catch (Exception ex) {
			// System.err.println("<TCPCLientConnectionMessageCollector> Error:" +
			// ex.getMessage());
		}
	}

	public void dispose() {
		try {
			fMyClient = null;
		} catch (Exception ex) {
		}
	}
}